package communications;

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * The EmailHandler class is responsible for everything concerning e-mails.
 * Uses SMTP servers of Gmail to send e-mails.
 *
 * @author Robin Persson
 */

public class EmailHandler {
	private final String password = "labtec",
	mailFrom = "reerazor@gmail.com",
	serverHost = "smtp.gmail.com",
	serverPort = "465",
	mailSubject = "Motivational Shoes";

	private String mailTo = "";
	
	private String[] beenAWhileStrings = {
			"You cannot plough a field by turning it over in your mind.",
			"Do not wait to strike till the iron is hot; but make it hot by striking. -William B. Sprague",
			"Nothing will ever be attempted if all possible objections must first be overcome. -Samuel Johnson",
			"He who hesitates is lost.",
			"Knowing is not enough; we must apply. Willing is not enough; we must do. -Johann Wolfgang von Goethe", 
			"Nothing great was ever achieved without enthusiasm. -Ralph Waldo Emerson",
			"They can because they think they can. -Virgil",
			"Nothing can stop the man with the right mental attitude from achieving his goal; nothing on earth can help the man with the wrong mental attitude. -Thomas Jefferson",
			"Keep steadily before you the fact that all true success depends at last upon yourself. -Theodore T. Hunger",
			"Success is the sum of small efforts, repeated day in and day out. -Robert Collier",
			"The thing always happens that you really believe in; and the belief in a thing makes it happen. -Frank Loyd Wright",
			"The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack in will. -Vince Lombardi",
			"The surest way not to fail is to determine to succeed. -Richard Brinsley Sheridan",
			"Whatever the mind can conceive and believe, the mind can achieve. -Napoleon Hill",
			"If you really want something, you can figure out how to make it happen. -Cher",
			"He that is good for making excuses is seldom good for anything else. -Benjamin Franklin",
			"Ninety-nine percent of failures come from people who have the habit of making excuses. -George W. Carver",
			"When I thought I couldn't go on, I forced myself to keep going. My success is based on persistence, not luck. -Estee Lauder",
			"Running is the greatest metaphor for life, because you get out of it what you put into it. -Oprah Winfrey",
			"The miracle isn't that I finished. The miracle is that I had the courage to start. -John Bingham, running speaker and writer",
			"Running is a big question mark that's there each and every day. It asks you, 'Are you going to be a wimp or are you going to be strong today?' -Peter Maher, Canadian marathon runner", 
			"Keep varying the program. Your body will tell you what to do. -Joan Benoit Samuelson ",
			"The difference between a jogger and a runner is an entry blank. -George Sheehan",
			"Anybody can be a runner. We were meant to move. We were meant to run. It's the easiest sport. -Bill Rodgers",
			"Mental will is a muscle that needs exercise, just like the muscles of the body. -Lynn Jennings",
			"Running is play, for even if we try hard to do well at it, it is a relief from everyday cares. -Jim Fixx", 
			"Everyone who has run knows that its most important value is in removing tension and allowing a release from whatever other cares the day may bring. -Jimmy Carter"
	};
	
	private String[] goodPerformanceStrings = {
			"Well done! Breaking new ground.",
			"Improvements!",
			"Great job out there!",
			"Victory means celebration!"
	};

	/**
     * Create a new EmailHandler, used for sending emails.
     * @param address - the receiving e-mail address 
	 */
	public EmailHandler(String address) {
		this.mailTo = address;
	}

	public void setAddress(String address) {
		this.mailTo = address;
	}

    /**
     * @return true if successful.
     */
    public void sendBeenAWhileEmail() {
    	int nString = 0;
    	
    	nString = (int) Math.floor(beenAWhileStrings.length * Math.random());
    	String message = beenAWhileStrings[nString];
    
    	sendEmail(message);
    }

    /**
     * @return true if successful.
     */
    public void sendGoodPerformanceEmail() {
    	int nString = 0;
    	
    	nString = (int) Math.floor(goodPerformanceStrings.length * Math.random());
    	String message = goodPerformanceStrings[nString];
    
    	sendEmail(message);
    }

    protected void sendEmail(String message) {
		Properties props = new Properties();
		props.put("mail.smtp.user", mailFrom);
		props.put("mail.smtp.host", serverHost);
		props.put("mail.smtp.port", serverPort);
		props.put("mail.smtp.starttls.enable","true");
		props.put("mail.smtp.auth", "true");
		//props.put("mail.smtp.debug", "true");
		props.put("mail.smtp.socketFactory.port", serverPort);
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		try {
			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getInstance(props, auth);
			//session.setDebug(true);

			MimeMessage msg = new MimeMessage(session);
			msg.setText(message);
			msg.setSubject(mailSubject);
			msg.setFrom(new InternetAddress(mailFrom));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
			Transport.send(msg);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
    }
    
    public static boolean isValid(String address){  
		String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = address;
		Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		
		return matcher.matches(); 
    }
    
	private class SMTPAuthenticator extends javax.mail.Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(mailFrom, password);
		}
	}
}